package org.netty.mvc.tool;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.netty.mvc.entity.ParamProperties;
import org.netty.mvc.http.ServerInitializer;

import java.io.IOException;
import java.net.InetAddress;
import java.security.cert.CertificateException;

public class NettyServer {


    //运行端口号，默认8080
    static int PORT = 8080;

    public static void start(ParamProperties property) {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // Configure SSL
        SslContext sslCtx = null;
        //默认不使用此协议
        boolean isSSL = false;

        try {

            //是否使用https协议
            if (property.getSslPort() == null) {
                PORT = property.getPort();
            } else {
                isSSL = true;
                PORT = property.getSslPort();
                SelfSignedCertificate ssc = new SelfSignedCertificate();
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
            }

            //bossGroup线程数设置
            if (property.getBossGroup() != null) {
                bossGroup = new NioEventLoopGroup(property.getBossGroup());
            }
            //workerGroup线程数设置
            if (property.getWorkerGroup() != null) {
                workerGroup = new NioEventLoopGroup(property.getWorkerGroup());
            }

            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    //自定义handler
                    .childHandler(new ServerInitializer(sslCtx));

            Channel ch = b.bind(PORT).sync().channel();

            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println("请求地址：" + (isSSL ? "https" : "http") + "://127.0.0.1:" + PORT + '/');
            System.out.println("请求地址：" + (isSSL ? "https" : "http") + "://" + localHost.getHostAddress() + ":" + PORT + '/');

            ch.closeFuture().sync();

        } catch (CertificateException | IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
